package com.itheima.reggie.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.AddressBookMapper;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.OrdersService;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {


    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;


    @Override
    public R submitOrder(Orders orders) {
        /*
            orders  +  order_detail
            张三        购物车
                       米饭     3份   2
                       辣子鸡丁  1份   88
                       酸菜鱼   1份   48

            购物车  --->  生成一个订单   orders 会有一条订单数据
            购物车中点的菜品或套餐数据  ---> 存入 订单明细表中  order_detail
         */
        //0、查询出购物车的数据
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId, UserHolder.getUserId());
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectList(qw);


        //1、保存订单数据
        //订单号：雪花生成算法
        Long orderNumber = IdWorker.getId();
        orders.setNumber(orderNumber.toString());
        orders.setStatus(1);
        orders.setOrderTime(LocalDateTime.now());
        // orders.setAmount(0);//来自于购物车数据
        BigDecimal totalAmount = new BigDecimal(0);
        for (ShoppingCart shoppingCart : shoppingCarts) {
            BigDecimal amount = shoppingCart.getAmount();
            Integer number = shoppingCart.getNumber();
            totalAmount = totalAmount.add( amount.multiply(new BigDecimal(number)));
        }
        orders.setAmount(totalAmount);
        //收货人相关信息：使用默认的收货人地址
        setAddress(orders);
        orders.setUserName(UserHolder.getUserName());
        orders.setUserId(UserHolder.getUserId());
        orders.setCheckoutTime(LocalDateTime.now());

        ordersMapper.insert(orders);


        //2、保存订单明细数据
        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtil.copyProperties(shoppingCart,orderDetail);
            orderDetail.setOrderId(orderNumber );
            orderDetailMapper.insert(orderDetail);
            shoppingCartMapper.deleteById(shoppingCart.getId());
        }
        //清空购物车

        return R.success("保存订单成功！");
    }

    private void setAddress(Orders orders) {
        AddressBook addressBook = addressBookMapper.selectById(orders.getAddressBookId());
        if(addressBook==null){
            //没有选择收获地址，则使用默认地址
            LambdaQueryWrapper<AddressBook> qw2 = new LambdaQueryWrapper<>();
            qw2.eq(AddressBook::getUserId, UserHolder.getUserId());
            qw2.eq(AddressBook::getIsDefault,1);
            addressBook = addressBookMapper.selectOne(qw2);
        }

        StringBuilder sb = new StringBuilder();
        if(StrUtil.isNotEmpty(addressBook.getProvinceName())) sb.append(addressBook.getProvinceName()).append("-");
        if(StrUtil.isNotEmpty(addressBook.getCityName())) sb.append(addressBook.getCityName()).append("-");
        if(StrUtil.isNotEmpty(addressBook.getDistrictName())) sb.append(addressBook.getDistrictName()).append("-");
        sb.append(addressBook.getDetail());
        orders.setAddress(sb.toString());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
    }
}
